package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Customer;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends MyHttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
	public void init() throws ServletException {
		//give me a connection to database!!!
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}
	
	private void process(HttpServletRequest request,
			HttpServletResponse response) {
		Document xmlDoc = getDocument(request);
		NodeList user = xmlDoc.getElementsByTagName("user").item(0).getChildNodes();
		String username = user.item(0).getFirstChild().getNodeValue();
		String password = user.item(1).getFirstChild().getNodeValue();
		try {
			printWriter = response.getWriter();
			response.setContentType("application/xml");
			if (verify(username,password)) {
				addTag("result", "okay");				
			} else {
				addTag("result", "denied");
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//TODO Connect the Database & Remove temp implement
	private boolean verify(String username, String password) {
		//TEMP IMPLEMENT
//		if (username.equals("etenaelta")
//				&& password.equalsIgnoreCase("123123123"))
//			return true;
//		else
//			return false;
		//TEMP IMPLEMENT END
		
		Customer user = new Customer();
		user.setName(username);
		user.setPassword(password);
		return persistence.Login.canLogin(user);
	}
}
